package com.it.jzs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.jzs.dao.BlogUserThumbsMapper;
import com.it.jzs.dao.admin.*;
import com.it.jzs.pojo.*;
import com.it.jzs.service.BlogService;
import com.it.jzs.util.ListPage;
import com.it.jzs.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {
    private static final Integer ZONGHE = 0;  // 排序标志
    private static final Integer TIME = 0;
    private static final Integer REMEN = 0;
    private static final Integer SELECT = 0;
    private static final Integer NOT_SELECT = 1;
    @Resource
    private AdminBlogMapper blogMapper;

    @Resource
    private AdminUserMapper userMapper;

    @Resource
    private BlogUserThumbsMapper blogUserThumbsMapper;

    @Resource
    private AdminTagMapper tagMapper;

    @Resource
    private AdminCustomMapper customMapper;
    @Resource
    private AdminSwiperMapper swiperMapper;
    @Resource
    private AdminTypeMapper typeMapper;

    @Resource
    private AdminBlogTagsMapper blogTagsMapper;

    //    test
    //    test
    @Override
    public Result<Object> selectBlogTypeList(Integer id) { // 博客分类列表页查询
        // 这里应该加层判断，因为分类的名字和图片都是从博客来的，这里的自定义SQL有问题，如果这个分类
        // 对应的没有对应的博客会查空，如果没有博客使用这个分类，那么就走这段逻辑
        List<BlogTypeListVo> listVoList = new ArrayList<>();
        Integer count = blogMapper.selectCount(new QueryWrapper<Blog>().eq("type_id", id));
        if (count != 0) {
            listVoList = blogMapper.selectBlogTypeList(id);
            for (BlogTypeListVo blogTypeListVo : listVoList) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Long time = Long.valueOf(blogTypeListVo.getCreateTime());
                Date date = new Date(time);
                String format = simpleDateFormat.format(date);
                blogTypeListVo.setFormatTime(format);
            }
        } else {
//            tagMapper.s
            Type type = typeMapper.selectById(id);
            String typeName = type.getName();
            String typeImg = type.getTypeImg();
            BlogTypeListVo blogTypeListVo = new BlogTypeListVo();
            blogTypeListVo.setTypeImg(typeImg);
            blogTypeListVo.setTypeName(typeName);
            listVoList.add(blogTypeListVo);


        }
        return Result.success(listVoList, "获取博客分类列表页成功！");


    }

    @Override
    public Result<Object> selectBlogTagList(Integer id) { // 博客标签列表页查询
        // 这里应该加层判断，因为分类的名字和图片都是从博客来的，这里的自定义SQL有问题，如果这个分类
        // 对应的没有对应的博客会查空，如果没有博客使用这个分类，那么就走这段逻辑
//        System.out.println("id = " + id);
        List<BlogTagListVo> blogTagListVos = new ArrayList<>();
        Integer count = blogTagsMapper.selectCount(new QueryWrapper<BlogTags>().eq("tags_id", id));
        if (count != 0) {
            blogTagListVos = blogMapper.selectBlogTagList(id);
            for (BlogTagListVo blogTagListVo : blogTagListVos) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Long time = Long.valueOf(blogTagListVo.getCreateTime());
                Date date = new Date(time);
                String format = simpleDateFormat.format(date);
                blogTagListVo.setFormatTime(format);
            }
        } else {
            Tag tag = tagMapper.selectById(id);
//            System.out.println("tag = " + tag);
            BlogTagListVo blogTagListVo = new BlogTagListVo();
            blogTagListVo.setTagImg(tag.getTagImg());
            blogTagListVo.setTypeName(tag.getName());
//            System.out.println("blogTagListVo = " + blogTagListVo);
            blogTagListVos.add(blogTagListVo);
        }
//        System.out.println("blogTagListVos.size() = " + blogTagListVos.size());
        return Result.success(blogTagListVos, "成功");

    }

    @Override
    public Result<Object> selectTagName(Integer id) {   // 根据id查询标签的名字
//        blogMapper
        Tag tag = tagMapper.selectById(id);
        return Result.success(tag, "获取标签数据成功");

    }

    @Override  // 这里num貌似没什么用
    public Result<Object> selectBlogByKeyWords(String keyWords, Integer index, Integer size, Integer num) { // 分页查询+模糊查询 博客标题和作者名字
//        num = num.equals(ZONGHE) ? ZONGHE : REMEN;
//        System.out.println("keyWords = " + keyWords);
        index = (index - 1) * size;
        List<BlogIndexVo> blogIndexVos = blogMapper.selectBlogByKeyWords(keyWords, index, size, num);
        List<BlogIndexVo> blogIndexVos1 = blogMapper.selectBlogByKeyWords(keyWords, 0, 0, num);
        int count = blogIndexVos1.size();
        for (BlogIndexVo blogIndexVo : blogIndexVos) {
            // 进行时间戳的转换
            String createTime = blogIndexVo.getCreateTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long time = Long.valueOf(createTime);
            Date date = new Date(time);
            String format = simpleDateFormat.format(date);
            blogIndexVo.setFormatTime(format);
        }
//        for (BlogIndexVo blogIndexVo : blogIndexVos) {
//            System.out.println("blogIndexVo = " + blogIndexVo);
//        }

//        Integer count = blogMapper.selectCount(null);
//        int pageAll = count % pagesize == 0 ? count / pagesize : (count / pagesize) + 1;
        HashMap<String, Object> map = new HashMap<>();
        map.put("blogList", blogIndexVos);
        map.put("total", count);
        return Result.success(map, "获取首页博客模糊查询分页列表成功");

    }

    @Override
    public Result<Object> selectBlogList(Integer index, Integer size, Integer num) {  // 查询首页博客分页列表
        // 因为是多表关联查询，肯定会有冗余的数据，其他相同，tagname不同的放在一个对象的集合里，
//        所以要按照博客id分组先查询出符合条件的总条数
        System.out.println("num = " + num);
        index = (index - 1) * size;
        List<BlogIndexVo> blogIndexVos = blogMapper.selectBlogIndex(index, size, num);  // 查出来符合条件的数据 多表查询
//        List<BlogIndexVo> list = ListPage.startPage(blogIndexVos, index, size);
        List<BlogIndexVo> blogIndexVos1 = blogMapper.selectBlogIndex(0, 0, num);  // 查询记录总数
        int count = blogIndexVos1.size();

//        int count = blogIndexVos.size(); // 查出来的数据原始符合条件的数据
        for (BlogIndexVo blogIndexVo : blogIndexVos) {   // 时间戳转换
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = blogIndexVo.getCreateTime();
            Long time = Long.valueOf(createTime);
            Date date = new Date(time);
            String format = simpleDateFormat.format(date);
            blogIndexVo.setFormatTime(format);
        }
//        for (BlogIndexVo blogIndexVo : blogIndexVos) {
//            System.out.println("blogIndexVo = " + blogIndexVo);
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("blogList", blogIndexVos);
        map.put("total", count);
//        System.out.println("list.size() = " + list.size());
        return Result.success(map, "获取首页博客分页列表成功");
    }


    @Override
    public Result<Object> selectLatestBlog() {   // 查询最新的博客
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        wrapper.last("limit 5");
        List<Blog> blogs = blogMapper.selectList(wrapper);
//        BeanUtils.copyProperties();
        ArrayList<BlogIndexLatestVo> list = new ArrayList<>();
        for (Blog blog : blogs) {
            BlogIndexLatestVo latestVo = new BlogIndexLatestVo();
            BeanUtils.copyProperties(blog, latestVo);
            list.add(latestVo);
        }
        return Result.success(list, "获取最新的博客");

    }

    @Override
    public Result<Object> selectCountBlog() {  // 查询每一年每个月的博客数量
        List<BlogIndexCountVo> blogIndexCountVos = blogMapper.selectCountBlog();
        return Result.success(blogIndexCountVos, "获取每一年每个月的博客数量成功");

    }

    @Override
    public Result<Object> selectCustom() {  // 获取首页自定义数据
        QueryWrapper<Custom> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("custom_id").last("limit 1");
        Custom custom = customMapper.selectOne(wrapper);
        return Result.success(custom, "获取首页自定义数据成功");

    }

    @Override
    public Result<Object> selectSwiper() {  // 获取轮播图
        List<Swiper> swiperList = swiperMapper.selectList(null);
        ArrayList<BlogIndexSwiper> list = new ArrayList<>();
        for (Swiper swiper : swiperList) {
            BlogIndexSwiper blogIndexSwiper = new BlogIndexSwiper();
            blogIndexSwiper.setSwiperImg(swiper.getSwiperImg());
            list.add(blogIndexSwiper);
        }
        return Result.success(list, "获取轮播图数据成功");
    }

    @Override
    public Result<Object> selectArchiveByTime(String time) {  // 根据每一年每个月的时间来取出相对应的博客列表
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        Long time1 = Long.valueOf(time);
//        System.out.println("time1 = " + time1);
        Date dateYear = new Date(time1);
        String year = simpleDateFormat.format(dateYear);
        simpleDateFormat = new SimpleDateFormat("M");  // 一个M 就是 9月是9  不是09
        Date dateMonth = new Date(time1);
        String month = simpleDateFormat.format(dateMonth).substring(0);
//        System.out.println("year = " + year);
//        System.out.println("month = " + month);
        List<BlogArchiveVo> blogArchiveVos = blogMapper.selectArchiveByTime(); // 得到所有数据
        ArrayList<BlogArchiveVo> list = new ArrayList<>();
        for (BlogArchiveVo blogArchiveVo : blogArchiveVos) {
            String year1 = blogArchiveVo.getYear().toString();  // 数据库表示的是09 ，但是取出来的却是9
            String month1 = blogArchiveVo.getMonth().toString();
//            System.out.println("year1 = " + year1);
//            System.out.println("month1 = " + month1);
            if (year1.equals(year) && month1.equals(month)) {
                list.add(blogArchiveVo);
            }
        }
        for (BlogArchiveVo blogArchiveVo : list) {
            System.out.println("blogArchiveVo = " + blogArchiveVo);
        }
        return Result.success(list, "获取归档数据成功");
    }

    @Override
    public Result<Object> selectBlogDetail(Integer id) {  // 博客详情页
//         先修改博客的浏览次数， +1 然后再查出来就是新增的
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        Blog blog = blogMapper.selectById(id);
        blog.setViews(blog.getViews() + 1);  // 自增1
        blogMapper.updateById(blog); // 修改次数
        BlogDetailVo blogDetailVo = blogMapper.selectBlogDetail(id);   // 连表查询博客详情数据
        // 转换时间戳&统计字数
        Long createTime = Long.valueOf(blogDetailVo.getCreateTime());
        Long updateTime = Long.valueOf(blogDetailVo.getUpdateTime());
        Date dateCreate = new Date(createTime);
        Date dateUpdate = new Date(updateTime);
        SimpleDateFormat create = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat create1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatSimply = simpleDateFormat.format(new Date(createTime));
        String formatCreate = create.format(dateCreate);
        String formatUpdate = create1.format(dateUpdate);
        blogDetailVo.setFormatCreate(formatCreate);
        blogDetailVo.setFormatUpdate(formatUpdate);
        blogDetailVo.setFormatSimply(formatSimply);
        blogDetailVo.setFirstPicture(blog.getFirstPicture());
        int count = 0;
        String content = blogDetailVo.getContent();
        char[] chars = content.toCharArray();
        boolean flag = false;  // 进行 <> 的判断
        for (int i = 0; i < chars.length; i++) {  // 字数的统计
            if (chars[i] == '<') {
                flag = false;
                continue;
            }
            if (chars[i] == '>') {
                flag = true;
            }
            if (flag)
                count++;
        }
        count = count - 2;
        blogDetailVo.setCount(count);
        return Result.success(blogDetailVo, "获取博客详情页成功");
    }


    @Override
    public Result<Object> updateThubms(Integer id, Integer userId) {
        User user = userMapper.selectById(userId);
        Blog blog = blogMapper.selectById(id);
        System.out.println("user = " + user);
        QueryWrapper<BlogUserThumbs> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("blog_id", id).orderByDesc("create_time").last("limit 1");
        // 查出最新的点赞记录
        BlogUserThumbs blogUserThumbs1 = blogUserThumbsMapper.selectOne(wrapper); // 查询之前是否点过赞

        if (blogUserThumbs1 != null) {  // 之前点过赞

            boolean flag = (System.currentTimeMillis() - blogUserThumbs1.getCreateTime()) > 86400000;  // 大于一天的话，可以点赞
            System.out.println("flag = " + flag);
            if (flag) {  // 如果过了一天，可以点赞
                BlogUserThumbs blogUserThumbs = new BlogUserThumbs();
                blogUserThumbs.setBlogId(id);
                blogUserThumbs.setFlag(SELECT); // 没有选择
                blogUserThumbs.setBlogTitle(blog.getTitle());
                blogUserThumbs.setCreateTime(System.currentTimeMillis());
                blogUserThumbs.setUserName(user.getNickname());
                blogUserThumbs.setUserId(userId);
                blog.setThumbs(blog.getThumbs() + 1);  // 博客点赞+1
                int i = blogMapper.updateById(blog);
                int insert = blogUserThumbsMapper.insert(blogUserThumbs); // 再插入一条的好处是，可以看你对这个博客点了多少次赞
                if (i > 0 && insert > 0) {
                    return Result.success(null, "点赞成功！");
                }
            } else {  // 还没过一天
                return Result.error(null, "今天已经点过赞了，请明天再来。");
            }
        } else {  // 没点过赞
            BlogUserThumbs blogUserThumbs = new BlogUserThumbs();
            blogUserThumbs.setBlogId(id);
            blogUserThumbs.setFlag(SELECT); // 没有选择
            blogUserThumbs.setBlogTitle(blog.getTitle());
            blogUserThumbs.setCreateTime(System.currentTimeMillis());
            System.out.println("user.getNickname() = " + user.getNickname());
            blogUserThumbs.setUserName(user.getNickname());
            blogUserThumbs.setUserId(userId);
//            int views = blog.getViews();
//            views = views == null ? 0 : views;
            Integer thumbs = blog.getThumbs();
            thumbs = thumbs == null ? 0 : thumbs;
            blog.setThumbs(thumbs + 1);  // 博客点赞+1
            int i = blogMapper.updateById(blog);
            int insert = blogUserThumbsMapper.insert(blogUserThumbs);
            if (i > 0 && insert > 0) {
                return Result.success(null, "点赞成功！");
            }
        }

        return Result.error(null, "点赞失败");
    }

    @Override
    public Result<Object> selectPlatform(Integer id) { // 用户个人中心博客

        List<BlogPlatFormVo> blogPlatFormVos = blogMapper.selectPlatform(id);// 根据用户id 查出对应的所属的博客，进行crud
        for (BlogPlatFormVo blogPlatFormVo : blogPlatFormVos) {
            Long createTime = blogPlatFormVo.getCreateTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(createTime);
            String format = simpleDateFormat.format(date);
            blogPlatFormVo.setFormatTime(format);
        }
        return Result.success(blogPlatFormVos, "获取数据成功");
    }

    @Override
    public Result<Object> deleteBlog(Integer id, Integer userId) { // 用户个人中心博客  根据博客id 删除博客
        List<Blog> blogList = blogMapper.selectList(new QueryWrapper<Blog>().eq("user_id", userId));
        boolean flag = false;
        int i = 0;
        for (Blog blog : blogList) {   // 看看删除的博客是不是属于这个用户的
//            System.out.println("blog = " + blog);
            Integer id1 = blog.getId();
            if (id1.equals(id)) {
                flag = true;
            }
        }
        if (flag) {
            i = blogMapper.deleteById(id);
        } else {
            return Result.error(null, "不属于你的博客");
        }
        if (i > 0) {
            return Result.success(null, "删除成功");
        }
        return Result.error(null, "删除失败！");


    }

//    @Override
//    public Result<Object> selectSArchiveByTime(Integer time) {
//        List<Blog> blogs = blogMapper.selectArchiveByTime();
//        return Result.success(null,null);
//
//    }


}
